// 用户管理
async function fetchUsers() {
    const response = await fetch('/api/users');
    const users = await response.json();
    const userList = document.getElementById('user-list');
    userList.innerHTML = '';
    Object.entries(users).forEach(([userId, user]) => {
        const li = document.createElement('li');
        li.textContent = `${user.name} (ID: ${userId})`;
        userList.appendChild(li);
    });
}

// 境界管理
async function fetchRealms() {
    const response = await fetch('/api/realms');
    const realms = await response.json();
    const realmTags = document.getElementById('realm-tags');
    realmTags.innerHTML = '';
    realms.forEach((realm, index) => {
        const tag = document.createElement('div');
        tag.className = 'realm-tag';
        tag.innerHTML = `
            <span>${realm}</span>
            <span class="delete-btn" onclick="deleteRealm(${index})">×</span>
        `;
        realmTags.appendChild(tag);
    });
}

async function addRealm() {
    const newRealm = document.getElementById('new-realm').value.trim();
    if (newRealm) {
        await fetch('/api/realms', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ realm: newRealm })
        });
        fetchRealms();
        document.getElementById('new-realm').value = '';
    }
}

async function deleteRealm(index) {
    if (confirm(`确定要删除这个境界吗?`)) {
        await fetch(`/api/realms/${index}`, { method: 'DELETE' });
        fetchRealms();
    }
}

// 妖怪管理
async function fetchMonsters() {
    const response = await fetch('/api/monsters');
    const monsters = await response.json();
    const monsterList = document.getElementById('monster-list');
    monsterList.innerHTML = '';
    monsters.forEach((monster, index) => {
        const div = document.createElement('div');
        div.className = 'monster-tag';
        div.innerHTML = `
            <span>${monster.name} (${monster.level})</span>
            <span class="delete-btn" onclick="deleteMonster(${index})">×</span>
        `;
        monsterList.appendChild(div);
    });
}

async function addMonster() {
    const name = document.getElementById('new-monster-name').value.trim();
    const level = parseInt(document.getElementById('new-monster-level').value);
    if (name && !isNaN(level)) {
        await fetch('/api/monsters', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name, level })
        });
        fetchMonsters();
        document.getElementById('new-monster-name').value = '';
        document.getElementById('new-monster-level').value = '';
    }
}

async function deleteMonster(index) {
    if (confirm(`确定要删除这个妖怪吗?`)) {
        await fetch(`/api/monsters/${index}`, { method: 'DELETE' });
        fetchMonsters();
    }
}

// 商店物品管理
async function fetchItems() {
    try {
        const response = await fetch('/api/items');
        const items = await response.json();
        const itemList = document.getElementById('item-list');
        itemList.innerHTML = '';
        items.forEach(item => {
            const li = document.createElement('li');
            li.textContent = `${item.name} (价格: ${item.price})`;
            li.onclick = () => showItemDetails(item);
            itemList.appendChild(li);
        });
    } catch (error) {
        console.error('获取物品列表时出错:', error);
    }
}

function showItemDetails(item) {
    const modal = document.getElementById('item-modal');
    document.getElementById('modal-item-name').textContent = item.name;
    document.getElementById('modal-item-price').textContent = `价格: ${item.price}`;
    document.getElementById('modal-item-description').textContent = item.description || '无描述';
    document.getElementById('modal-item-effect').textContent = `效果: ${JSON.stringify(item.effect)}`;
    document.getElementById('delete-item-btn').onclick = () => deleteItem(item.name);
    modal.style.display = 'block';
}

async function addItem() {
    const name = document.getElementById('new-item-name').value.trim();
    const price = parseInt(document.getElementById('new-item-price').value);
    const description = document.getElementById('new-item-description').value.trim();
    const effectType = document.getElementById('new-item-effect-type').value;
    const effectValue = parseInt(document.getElementById('new-item-effect-value').value);
    const effectAttribute = document.getElementById('new-item-effect-attribute').value.trim();
    const effectDuration = parseInt(document.getElementById('new-item-effect-duration').value);

    if (name && !isNaN(price)) {
        const effect = {};
        effect[effectType] = {
            value: effectValue,
            attribute: effectAttribute,
            duration: effectDuration
        };

        try {
            await fetch('/api/items', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, price, description, effect: JSON.stringify(effect) })
            });
            fetchItems();
            // 清空输入字段
            document.getElementById('new-item-name').value = '';
            document.getElementById('new-item-price').value = '';
            document.getElementById('new-item-description').value = '';
            document.getElementById('new-item-effect-type').value = '';
            document.getElementById('new-item-effect-value').value = '';
            document.getElementById('new-item-effect-attribute').value = '';
            document.getElementById('new-item-effect-duration').value = '';
        } catch (error) {
            console.error('添加物品时出错:', error);
        }
    }
}

async function deleteItem(itemName) {
    if (confirm(`确定要删除 ${itemName} 吗?`)) {
        try {
            await fetch(`/api/items/${encodeURIComponent(itemName)}`, { method: 'DELETE' });
            fetchItems();
            document.getElementById('item-modal').style.display = 'none';
        } catch (error) {
            console.error('删除物品时出错:', error);
        }
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('login-container').style.display = 'flex';
    document.getElementById('app').style.display = 'none';

    document.querySelectorAll('#sidebar a').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            showSection(e.target.dataset.section);
        });
    });

    document.querySelector('.close').onclick = () => {
        document.getElementById('item-modal').style.display = 'none';
    };

    window.onclick = (event) => {
        if (event.target == document.getElementById('item-modal')) {
            document.getElementById('item-modal').style.display = 'none';
        }
    };
});

function showSection(sectionId) {
    document.querySelectorAll('section').forEach(section => {
        section.classList.add('hidden');
    });
    document.getElementById(sectionId).classList.remove('hidden');
}

async function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password }),
        });

        const result = await response.json();

        if (result.success) {
            document.getElementById('login-container').style.display = 'none';
            document.getElementById('app').style.display = 'flex';
            // 初始化应用
            fetchUsers();
            fetchRealms();
            fetchMonsters();
            fetchItems();
            showSection('users');
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('登录时出错:', error);
        alert('登录失败,请稍后再试。');
    }
}
